package com.lv.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lv.api.CartServiceApi;
import com.lv.api.GoodsServiceApi;
import com.lv.api.UserServiceApi;
import com.lv.data.Result;
import com.lv.dto.AddressDto;
import com.lv.dto.CartDeailDto;
import com.lv.dto.CartDto;
import com.lv.dto.ItemDto;
import com.lv.mapper.TbOrderItemMapper;
import com.lv.mapper.TbOrderMapper;
import com.lv.model.TbOrder;
import com.lv.model.TbOrderItem;
import com.lv.service.OrderService;
import com.lv.util.IdWorker;
import com.lv.util.JwtUtil;
import com.lv.util.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private TbOrderMapper om;

    @Resource
    private TbOrderItemMapper oim;

    @Resource
    private CartServiceApi cApi;

    @Resource
    private IdWorker idWorker;

    @Resource
    private UserServiceApi uApi;

    @Resource
    private GoodsServiceApi gApi;

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redis;

    @Autowired
    private JwtUtil jwtUtil;

    //提交订单

    @Override                     //事务  数据库有事务
    @Transactional
    public void submitOrder(String AutharizeToken, Long addressId, String payType) {
        // 1, 根据用户的信息从购物车系统中取出购物车数据
        Result cartResult = cApi.getCart(AutharizeToken);
        List<CartDto> cartDtoList = JSONObject.parseArray(JSONObject.toJSONString(cartResult.getData()), CartDto.class);
        Claims claims = jwtUtil.parseJwt(AutharizeToken);
        LoginUser loginUser = JSONObject.parseObject(claims.getSubject(), LoginUser.class);
        //查询收货地址
        Result<AddressDto> result = uApi.getAddressById(addressId);
        AddressDto addressDto = result.getData();
        //定义集合接收订单主表数据
        List<TbOrder> orderList = new ArrayList<>();
        //定义一个集合接收订单明细
        List<TbOrderItem> orderItemList = new ArrayList();
        //扣减库存
        List<ItemDto> itemDtoList = new ArrayList<>();
        //遍历购物车保存订单
        for (CartDto cartDto : cartDtoList) {
            //生成订单ID
            long orderId = idWorker.nextId();
            //创建订单对象
            TbOrder order = new TbOrder();
            order.setOrderId(orderId); //主键
            order.setUserId(loginUser.getUsername()); //买家
            order.setPaymentType(payType); //支付类型
            order.setStatus("1"); //未付款
            order.setCreateTime(new Date()); //创建时间
            order.setUpdateTime(new Date()); //更新时间
            order.setReceiverAreaName(addressDto.getAddress()); //收货地址
            order.setReceiverMobile(addressDto.getMobile()); //手机号
            order.setReceiver(addressDto.getContact()); //联系人
            order.setSellerId(cartDto.getSellerId()); //商家Id
//            order.setPaymentTime(new Date()); // 付款时间
            //定义一个变量计算求和的
            BigDecimal sum = new BigDecimal(0);
            //循环明细
            for (CartDeailDto cartDeailDto : cartDto.getDetaillist()) {
                //总价
                sum = sum.add(cartDeailDto.getTotalFee());
                //创建明细对象
                TbOrderItem orderItem = new TbOrderItem();
                orderItem.setGoodsId(cartDeailDto.getGoodsId());
                orderItem.setId(idWorker.nextId());//主键
                orderItem.setItemId(cartDeailDto.getItemId()); //商品的Id
                orderItem.setNum(cartDeailDto.getNum()); //购买的商品数量
                orderItem.setOrderId(orderId); //订单主表的Id
                orderItem.setPicPath(cartDeailDto.getPicPath()); //图片地址
                orderItem.setPrice(cartDeailDto.getPrice()); //单价
                orderItem.setSellerId(cartDeailDto.getSellerId()); //商家的Id
                orderItem.setTitle(cartDeailDto.getTitle()); //商品名
//                orderItem.setStatus("1")//待支付
                orderItem.setTotalFee(cartDeailDto.getTotalFee()); //小计
                orderItemList.add(orderItem);
                //----------------------扣减库存需要的数据
                ItemDto itemDTO = new ItemDto();
                itemDTO.setId(cartDeailDto.getItemId());
                itemDTO.setNum(cartDeailDto.getNum());
                itemDtoList.add(itemDTO);
            }
            order.setPayment(sum);//实付金额
            //保存
            orderList.add(order);
        }
        //扣减库存
        gApi.subStockCount(itemDtoList);
        //保存主表数据
        om.insertBatch(orderList);
        //保存明细表数据
        oim.insertBatch(orderItemList);

        System.out.println(cartResult);
        // TODO 删除购物车
        redis.boundHashOps("cartList").delete(loginUser.getId());

    }











}
